package parkshop.pmcourse.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import parkshop.pmcourse.service.FileUploadService;
import parkshop.pmcourse.utils.FileTools;

/**
 * Created by Administrator on 2016/9/25.
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {


    private static final Logger LOGGER = LoggerFactory.getLogger(FileUploadServiceImpl.class);

  /*
   * (non-Javadoc)
   * @see parkshop.pmcourse.service.FileUploadService#uploadPic(javax.servlet.http.HttpServletRequest)
   * 
   * 获取 request 中的图片并返回图片存储的路径
   */
    
    @Override
    public String uploadPic(HttpServletRequest request) {
    	
    	MultipartFile multipartFile = getMultipartFile(request);
    	//设置图片名称
    	String suffix=FileTools.getSuffix(multipartFile.getOriginalFilename());
    	String fileName = FileTools.getFileName(suffix);
    	String path=FileTools.getFilePath(suffix);
    	File targetFile = new File(path + File.separatorChar + fileName);    		
    		try {
				multipartFile.transferTo(targetFile);
			} catch (IllegalStateException | IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				LOGGER.debug(e.getMessage());
				return null;
			}
    		
    	String serverName=request.getServerName()+":"+request.getServerPort();
    	String url="/image/get/"+FileTools.removeDot(fileName);
    		return url;//保存在本机的绝对路径
    }

 

    private MultipartFile getMultipartFile(HttpServletRequest request) {
    	
        MultipartHttpServletRequest multipartRequest =new StandardMultipartHttpServletRequest(request);
        Iterator<String> fileNames = multipartRequest.getFileNames();
        return multipartRequest.getFile(fileNames.next());
    }
}
